package com.yztc.xiami_app.ui.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.yztc.xiami_app.R;
import com.yztc.xiami_app.adapter.goodsdetails.DetailGoodsAdapter;
import com.yztc.xiami_app.bean.classify.ClassifiBean;
import com.yztc.xiami_app.http.OkHttpUtils;
import com.yztc.xiami_app.ui.activity.DetailActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class DetailFragment extends Fragment implements DetailGoodsAdapter.IOnItemClickListener{
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.recycle)
    RecyclerView recycle;
    //数据的url
    private String url = "http://m.ttcj.tv/xml/appcategoryjson.htm";
    private  String title;

    //页面的类型
    private int type;

    //分类商品的数据源
    private List<ClassifiBean.CatelistBean.Category2Bean> goodslist;
    //适配器
    private DetailGoodsAdapter mGoodsAdapter;

    public static final int STATE_UPDETE = 100;
    public static final int STATE_REFRESH_OVER = 101;
    //刷新画面的Hanndler
    private Handler updateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == STATE_UPDETE) {
                mGoodsAdapter.notifyDataSetChanged();
            }
            if (msg.what == STATE_REFRESH_OVER) {
                refreshLayout.setRefreshing(false);
            }

        }
    };
    //当前页数
    private int currentPage = 1;
    public DetailFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_detail, container, false);
        ButterKnife.bind(this, view);
        //取类型
        Bundle bundle = getArguments();
        //type = bundle.getInt(URLConstant.KEY_FRAGMENT_TEY);
        url = bundle.getString(ClassifyFragment.TAG);

        //从网络取数据
        getData(currentPage);
        //加载视图
        initView();
        //下拉刷新
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //从网络取数据
                currentPage++;
                getData(currentPage);
            }
        });
        return view;
    }

    private void initView() {
        goodslist = new ArrayList<>();
        mGoodsAdapter = new DetailGoodsAdapter(getActivity(), goodslist, this);
        GridLayoutManager layoutManager=new GridLayoutManager(getActivity(),3);
        layoutManager.getSpanSizeLookup();
        layoutManager.setSpanCount(2);
        recycle.setLayoutManager(layoutManager);
        recycle.setAdapter(mGoodsAdapter);
    }

    private void getData(int page) {
        OkHttpUtils.doGETRequest(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = updateHandler.obtainMessage();
                msg.what = STATE_REFRESH_OVER;
                updateHandler.sendMessage(msg);
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = updateHandler.obtainMessage();
                msg.what = STATE_REFRESH_OVER;
                updateHandler.sendMessage(msg);
                String result = OkHttpUtils.getStringFromResponse(response);
                //json解析
                Gson gson = new Gson();
                ClassifiBean classifiBean = gson.fromJson(result, ClassifiBean.class);
                List<ClassifiBean.CatelistBean> catelist = classifiBean.getCatelist();
                for(int i=0;i<catelist.size();i++){
                    ClassifiBean.CatelistBean catelistBean = catelist.get(i);
                    List<ClassifiBean.CatelistBean.Category2Bean> category2 = catelistBean.getCategory2();
                    for(int j=0;j<category2.size();j++){
                        goodslist.add(category2.get(j));
                    }

                }
                    Message msg2 = updateHandler.obtainMessage();
                    msg2.what = STATE_UPDETE; //
                    updateHandler.sendMessage(msg2);
            }
        });
    }
   @Override
    public void onclick(int position) {
        //点击item跳转到详情画面
        String strurl = goodslist.get(position).getUrl();
        String strtitle = goodslist.get(position).getTitle();
        Intent intent = new Intent(getActivity(), DetailActivity.class);
        intent.putExtra(url, strurl);
        intent.putExtra(title, strtitle);
        startActivity(intent);
    }
}
